/*
 * Copyright (c) 2011-2012 Alexander Dubu
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * o  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * o  Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * o  Neither the name Axil nor the names of its contributors may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package axil.stdlib.collection.type;

import axil.api.AxilObject;
import axil.api.AxilType;
import axil.api.error.AxilException;
import axil.api.extend.Environment;
import axil.api.extend.Parameters;
import axil.framework.type.Added;
import axil.framework.type.Concatenated;
import axil.framework.type.Sized;
import axil.stdlib.core.type.Nil;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static axil.framework.Functions.*;


/**
 * The base class for all Axil collections. Axil provides a unified collections
 * framework, so all collections (sets, maps, lists, etc) descend from a common
 * place and support a common set of methods.
 */
public abstract class AxilCollection<T extends AxilObject>
	implements AxilObject, Iterable<T>, Sized, Concatenated
{
	/**
	 * Tell if new instances of this type can be created by a script. All Axil
	 * types in the standard library can be created if that module in which
	 * they appear is visible to a script. However, the host application will
	 * typically want to prevent creation of new host application objects.
	 *
	 * @return
	 * 	Returns true if a script can create instances of this type. Even if
	 * 	false is returned, Java code may still create instances of this type.
	 */
	public boolean creatable() {
		return true;
	}


	/**
	 * Get the values for this collection. For most collections, this simply
	 * returns this object, but for complex collections such as dictionary, it
	 * returns the values.
	 */
	public AxilCollection<T> values() {
		return this;
	}


	/**
	 * Concatenate the given object onto this object, returning a new object.
	 * Neither this object nor the given object are altered. The given object
	 * is never null or nil, but may not be an object of the expected type.
	 */
	public AxilObject concatenate(AxilObject other)	{
        if (other == Nil.object) {
            return Nil.object;
        }
        // Only if this collection supports Add to we add/concatenate.
        if (this instanceof Added) {
			return ((Added)this).add(other);
		}
		throw error(axil(), "invalid-operand",
			  nv("operator", "&"), nv("type", other.type()));
	}


	/**
	 * Tell if this collection contains the value (not the key) given.
	 */
	public abstract boolean has(AxilObject object);


	/**
	 * Tell if this object is exactly equal to the given object. Exact equality
	 * takes type, order and all aspects of the object into consideration. An
	 * object can only be exactly equal to another if it is the exact same type.
	 * The object given is never null. The object given may be of any type of
	 * value object. If the given object is not a suitable type for comparison,
	 * a ClassCastException may be thrown.
     *
     * @see AxilObject#exactly(axil.api.AxilObject)
	 */
	public boolean exactly(AxilObject object)
	{
		if (object.type() == this.type()) {
			return equalTo(object);
		}
		return false;
	}


	/**
	 * Tell if this object is roughly equivalent to the given object. That is,
	 * would a non-technical person consider the objects equivalent? For example,
	 * a list(1,2,3) is equivalent to the list(3,2,1), but those lists are not
	 * exactly equal. The object given is never null. The object given may be
	 * of any type of value object. If the given object is not a suitable type
	 * for comparison, a ClassCastException may be thrown.
	 */
	public boolean equivalentTo(AxilObject object)
	{
		if (this == object) {
			return true;
		}
		return equalTo(object);
	}


	/**
	 * Indicates whether some other object is "equal to" this one. Two
	 * collections are considered equal if they contain the same objects,
	 * regardless of order.
	 */
	public boolean equals(Object obj) {
		if (obj == null) {
			return false;
		}
		if (this == obj) {
			return true;
		}
		if (obj == Nil.object) {
			return false;
		}
		if (obj instanceof AxilCollection)
		{
			return sameAs((AxilCollection)obj);
		}
		return equalTo((AxilObject) obj);
	}


	/**
	 * Indicates whether some other object is "equal to" this one. Two
	 * collections are considered equal if they contain the same objects,
	 * regardless of order.
	 */
	protected boolean sameAs(AxilCollection objects) {
		AxilCollection<T> a = this.values();
		AxilCollection<T> b = objects.values();
		if (a.size() != b.size()) {
			return false;
		}
		for (T o : a) {
			if (!b.has(o)) {
                return false;
            }
		}
		return true;
	}


    /**
     * Compares this object with the specified object for order.  Returns a
     * negative integer, zero, or a positive integer as this object is less
     * than, equal to, or greater than the specified object.
     */
    public int compareTo(AxilObject o) {
        return comparedTo(o);
    }

    /**
     * Compares this object with the specified object for order. If the given
     * object is not a suitable type for comparison, a ClassCastException may
     * be thrown.
     *
     * @param object
     * 	The object to compare against. The given object cannot be null but may
     * 	be any Axil object.
     *
     * @return
     * 	Returns a negative integer, zero, or a positive integer as this object
     * 	is less than, equal to, or greater than the specified object.
     */
    public int comparedTo(AxilObject object) {
        // This is the default implementation.
        if (object instanceof AxilCollection) {
            return this.size() - ((AxilCollection)object).size();
        }
        if (object instanceof Range) {
            return this.size() - ((Range)object).size();
        }
        // "nil" comparison; always return 1 (nil less than everything).
        if (object == Nil.object) {
            return 1;
        }
        // Incorrect comparison.
        throw error(axil(), "order-comparison",
                nv("this", this.type()),
                nv("that", object.type()));
    }


    /**
	 * Tell if this object, represents a true or false value. In general, true
	 * is returned for any object that is not equivalent to nil, is a number
	 * greater than zero, or is the boolean true value.
	 */
	public boolean bool() {
		return ! empty();
	}


	/**
	 * Tell if this collection is empty. Use of this method is much preferred
	 * over the idiom 'size() == 0' since determination of size may not be a
	 * constant time operation.
	 */
	public boolean empty() {
		return size() == 0;
	}


	/**
	 * Return the host application (or built-in Java) object that most closely
	 * matches this value object. Return returned value is never null unless
	 * this value object represents the special 'nil' object.
	 */
	public Object intrinsic() {
		List n = new ArrayList<T>();
		for (T v : this) {
			n.add(v.intrinsic());
		}
		return n;
	}


	/**
	 * Coerce this object into an instance of the given type. If this object
	 * cannot be meaningfully represented as an instance of that type, then an
	 * exception is thrown.
	 *
	 * @param type
	 * 	The type to be coerced to. The object given cannot be null.
	 *
	 * @return
	 * 	Returns an instance of the given type. If this object is nil, then nil
	 * 	is returned.
	 */
	public AxilObject coerce(AxilType type) throws AxilException {
		if (type == type()) {
			return this;
		}
		if (type == Dict.type) {
			/*
			 * Cannot convert other types of collections into a dictionary,
			 * since we do not have key information.
			 */
			throw error(axil(), "cannot-coerce-object",
			            nv("from", type()), nv("to", type));
		}
		if (type == Arry.type) {
			AxilObject[] values = new AxilObject[size()];
			int i = 0;
			for (AxilObject o : this) {
				values[i] = o;
				i++;
			}
			return new Arry(values).immute();
		}
		throw error(axil(), "cannot-coerce-object",
		            nv("from", type()), nv("to", type));
	}


	/**
	 * Evaluate this object in the given context and environment.
	 *
	 * @param env
	 * 	The environment in which the function is being invoked. The environment
	 * 	is never null.
	 *
	 * @param params
	 * 	The parameters to the function, which can be any Axil object. The values
	 * 	given are never null but may be the nil object (Axil.NIL).
	 */
	public AxilObject eval(Environment env, Parameters params) {
		return this;
	}


	static final class Safe<T> implements Iterator<T> {
		private Iterator<T> iter;

		Safe(Iterator<T> iter)		{
			this.iter = iter;
		}
		public boolean hasNext()	{
			return iter.hasNext();
		}
		public T next()				{
			return iter.next();
		}

		public void remove() {
			throw new UnsupportedOperationException(
			    "The underlying collection is immutable.");
		}
	}


	/**
	 * Convert each of the elements contained in this collection into a string
	 * (via their toString() method) and add each to a string separated by the
	 * given separator.
	 */
	public String separated(String separator) {
		StringBuilder b = new StringBuilder();
		for (T v : this) {
			if (b.length() > 0) {
				b.append(separator);
			}
			b.append(fmt(v));
		}
		return b.toString();
	}


	/**
	 * Return a string representation of this object. The string returned is
	 * never null.
	 */
	public String toString() {
		return separated(", ");
	}

    // Abstract methods
    public abstract AxilObject put(T object);

    /**
     * Mark this object as immutable, preventing any further changes. Any
     * attempt to alter this collection after this point results in an exception.
     */
    public abstract AxilCollection<T> immute();
}
